<template>
  <div class="user-transaction-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>我的交易</span>
        </div>
      </template>
      
      <el-tabs v-model="activeTab">
        <el-tab-pane label="全部交易" name="all">
          <transaction-list :data="transactionList" :loading="loading" @view="handleView" />
        </el-tab-pane>
        <el-tab-pane label="进行中" name="inProgress">
          <transaction-list :data="inProgressList" :loading="loading" @view="handleView" />
        </el-tab-pane>
        <el-tab-pane label="已完成" name="completed">
          <transaction-list :data="completedList" :loading="loading" @view="handleView" />
        </el-tab-pane>
        <el-tab-pane label="已取消" name="cancelled">
          <transaction-list :data="cancelledList" :loading="loading" @view="handleView" />
        </el-tab-pane>
      </el-tabs>

      <!-- 查看交易详情对话框 -->
      <el-dialog
        title="交易详情"
        v-model="viewDialogVisible"
        width="700px"
        append-to-body
      >
        <el-descriptions :column="2" border>
          <el-descriptions-item label="交易ID">{{ viewForm.id }}</el-descriptions-item>
          <el-descriptions-item label="交易日期">{{ formatDate(viewForm.transactionDate) }}</el-descriptions-item>
          <el-descriptions-item label="车辆ID">{{ viewForm.carId }}</el-descriptions-item>
          <el-descriptions-item label="经销商ID">{{ viewForm.dealerId }}</el-descriptions-item>
          <el-descriptions-item label="成交价格">{{ formatPrice(viewForm.price) }}</el-descriptions-item>
          <el-descriptions-item label="支付方式">{{ viewForm.paymentMethod }}</el-descriptions-item>
          <el-descriptions-item label="支付状态">
            <el-tag :type="getPaymentStatusType(viewForm.paymentStatus)">
              {{ formatPaymentStatus(viewForm.paymentStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="交易状态">
            <el-tag :type="getTransactionStatusType(viewForm.status)">
              {{ formatTransactionStatus(viewForm.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="合同文件" :span="2">
            <el-link v-if="viewForm.contractUrl" type="primary" :href="viewForm.contractUrl" target="_blank">
              查看合同
            </el-link>
            <span v-else>暂无合同</span>
          </el-descriptions-item>
        </el-descriptions>

        <template v-if="viewForm.car">
          <h3 class="detail-title">车辆信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="车牌号">{{ viewForm.car.carNumber }}</el-descriptions-item>
            <el-descriptions-item label="品牌">{{ viewForm.car.carBrand }}</el-descriptions-item>
            <el-descriptions-item label="指导价">{{ formatPrice(viewForm.car.guidePrice) }}</el-descriptions-item>
          </el-descriptions>
        </template>

        <template v-if="viewForm.dealer">
          <h3 class="detail-title">经销商信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="经销商名称">{{ viewForm.dealer.dealerName }}</el-descriptions-item>
            <el-descriptions-item label="联系人">{{ viewForm.dealer.contactPerson }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ viewForm.dealer.contactPhone }}</el-descriptions-item>
          </el-descriptions>
        </template>

        <div v-if="viewForm.status === 0" class="transaction-actions">
          <el-button type="primary" @click="handlePay" :disabled="viewForm.paymentStatus === 1">
            {{ viewForm.paymentStatus === 0 ? '支付' : '已支付' }}
          </el-button>
          <el-button type="danger" @click="handleCancel">取消交易</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getUserTransactions, 
  getTransactionById,
  updateTransactionStatus,
  updatePaymentStatus,
  formatPaymentStatus as formatPaymentStatusUtil,
  formatTransactionStatus as formatTransactionStatusUtil
} from '@/api/transaction'
import TransactionList from './components/TransactionList.vue'

// 当前用户ID（从用户状态或登录信息中获取）
const userId = ref(101) // 这里应该从用户状态中获取，暂时使用测试数据

// 活动标签
const activeTab = ref('all')
// 数据加载状态
const loading = ref(false)
// 交易列表数据
const transactionList = ref([])
// 筛选后的列表
const inProgressList = computed(() => transactionList.value.filter(item => item.status === 0))
const completedList = computed(() => transactionList.value.filter(item => item.status === 1))
const cancelledList = computed(() => transactionList.value.filter(item => item.status === 2))

// 查看表单参数
const viewForm = ref({})
// 对话框显示状态
const viewDialogVisible = ref(false)

// 获取用户交易列表
const getUserTransactionList = async () => {
  loading.value = true
  try {
    const res = await getUserTransactions(userId.value)
    transactionList.value = res || []
  } catch (error) {
    console.error('获取交易列表失败:', error)
    ElMessage.error('获取交易列表失败')
  } finally {
    loading.value = false
  }
}

// 查看详情
const handleView = async (row) => {
  try {
    const res = await getTransactionById(row.id)
    viewForm.value = res
    viewDialogVisible.value = true
  } catch (error) {
    console.error('获取交易详情失败:', error)
    ElMessage.error('获取交易详情失败')
  }
}

// 处理支付
const handlePay = () => {
  ElMessageBox.confirm('确认支付此订单吗?', '支付确认', {
    confirmButtonText: '确认支付',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await updatePaymentStatus(viewForm.value.id, 1)
      ElMessage.success('支付成功')
      viewDialogVisible.value = false
      getUserTransactionList()
    } catch (error) {
      console.error('支付失败:', error)
      ElMessage.error('支付失败')
    }
  }).catch(() => {})
}

// 取消交易
const handleCancel = () => {
  ElMessageBox.confirm('确认取消此交易吗?', '取消确认', {
    confirmButtonText: '确认取消',
    cancelButtonText: '不取消',
    type: 'warning'
  }).then(async () => {
    try {
      await updateTransactionStatus(viewForm.value.id, 2)
      ElMessage.success('交易已取消')
      viewDialogVisible.value = false
      getUserTransactionList()
    } catch (error) {
      console.error('取消交易失败:', error)
      ElMessage.error('取消交易失败')
    }
  }).catch(() => {})
}

// 格式化支付状态
const formatPaymentStatus = (status) => {
  return formatPaymentStatusUtil(status)
}

// 格式化交易状态
const formatTransactionStatus = (status) => {
  return formatTransactionStatusUtil(status)
}

// 获取支付状态对应的标签类型
const getPaymentStatusType = (status) => {
  const statusMap = {
    0: 'warning',
    1: 'success',
    2: 'info'
  }
  return statusMap[status] || 'info'
}

// 获取交易状态对应的标签类型
const getTransactionStatusType = (status) => {
  const statusMap = {
    0: 'primary',
    1: 'success',
    2: 'danger'
  }
  return statusMap[status] || 'info'
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 格式化价格
const formatPrice = (price) => {
  if (price === undefined || price === null) return '¥0.00'
  return `¥${Number(price).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
}

// 页面加载时获取交易列表
onMounted(() => {
  getUserTransactionList()
})
</script>

<style scoped>
.user-transaction-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.transaction-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 16px;
}

.detail-title {
  margin-top: 20px;
  margin-bottom: 10px;
  font-weight: bold;
  border-left: 4px solid #409eff;
  padding-left: 10px;
}
</style> 